<template>
  <div class="authorize">
    <el-form :model="form" label-width="auto">
      <el-form-item label="授权文件">
        <el-input v-model="form.fileName" disabled />
      </el-form-item>
      <el-form-item label="授权模式">
        <el-select v-model="form.mode" disabled>
          <el-option label="指定人员" value="1" />
          <el-option label="指定部门" value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    <el-button type="primary" size="small" style="margin-bottom: 12px;" @click="staffDialog"> <el-icon>
        <Plus />
      </el-icon>新增</el-button>
    <div class="table-container cont-table">
      <el-table :data="tableData" border stripe max-height="330px" class="custom-table">
        <el-table-column type="index" width="60" label="序号" />
        <template v-for="(item, index) in tabHeading">
          <el-table-column v-if="item.prop == 'auth'" :prop="item.prop" :label="item.label" :width="item.width"
            :min-width="item.minWidth" :formatter="formatAuth" />
          <el-table-column v-else :prop="item.prop" :label="item.label" :width="item.width" :min-width="item.minWidth">
          </el-table-column>
        </template>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openStaffAuth(row)">修改权限</el-button>
            <el-button link type="danger" size="small" @click="staffDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="addStaffDialog" title="新增成员" width="250px">
      <div style="margin-bottom: 16px;">
        <p style="margin-bottom: 8px;">请选择操作权限：</p>
        <el-select v-model="staffAuth" placeholder="设置权限">
          <el-option label="仅搜索" value="1" />
          <el-option label="仅查看" value="2" />
          <el-option label="可编辑" value="3" />
          <el-option label="可管理" value="4" />
        </el-select>
      </div>
      <div class="table-container cont-table">
        <p style="margin-bottom: 8px;">请选择员工：</p>
        <el-table @selection-change="handleSelectionChange" :data="staffData" border stripe max-height="200px"
          class="custom-table">
          <el-table-column type="selection" width="40" />
          <el-table-column type="index" width="53" label="序号" />
          <el-table-column label="员工姓名" prop="staffname" />
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addStaffDialog = false" size="small">取消</el-button>
          <el-button type="primary" @click="addStaff" size="small">
            新增
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="staffAuthDialog" title="修改权限" width="250px">
      <el-select v-model="staffAuth" placeholder="设置权限">
        <el-option label="仅搜索" value="1" />
        <el-option label="仅查看" value="2" />
        <el-option label="可编辑" value="3" />
        <el-option label="可管理" value="4" />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="staffAuthDialog = false" size="small">取消</el-button>
          <el-button type="primary" @click="editAuth" size="small">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from "@/api/httpApi.js"
import { cancelAllPendingRequests } from "@/api/request.js"
import { useUserStore } from '@/api/store'
// 存储当前页面所有未完成请求的取消函数
// const activeRequests = [];

const userStore = useUserStore()


// 用户信息
const userInfo = userStore.userInfo
// 权限映射配置
const authMap = {
  '1': '仅搜索',
  '2': '仅查看',
  '3': '可编辑',
  '4': '可管理'
};

const props = defineProps({
  folderData: {
    type: Object,
    default: {}
  }
})

const form = ref({
  fileName: "",
  mode: "1",//初期只有指定人员
})
const addStaffDialog = ref(false)
const staffAuthDialog = ref(false)
const tabHeading = ref([
  { prop: "staffname", label: "授权对象", width: "", minWidth: "", },
  { prop: "auth", label: "权限", width: "", minWidth: "", },
  // { prop: "tiem", label: "授权时间", width: "", minWidth: "", },
])
const staffAuth = ref("1")//员工权限
const staffAuthInfo = ref({})//用于存储需要修改权限的员工信息
const tableData = ref([])
const staffData = ref([])
const selectionArr = ref([])
const openStaffAuth = (row) => {
  staffAuthInfo.value = row
  staffAuth.value = row.auth
  staffAuthDialog.value = true
}
const staffDialog = async () => {
  api.getUserList({ userid: userInfo.id }).then((res) => {
    const userList = res.data.userList.map(item => ({
      userId: item.id,
      staffname: item.staffname,
      ...item
    }))
    staffData.value = userList
  })
  staffAuth.value = "1"
  addStaffDialog.value = true
}
// 修改权限
const editAuth = () => {
  let data = {
    parentid: userInfo.id,
    userid: staffAuthInfo.value.userId,
    proid: props.folderData.id,
    auth: staffAuth.value
  }
  api.RelevanceUpdate(data).then((res) => {
    if (res.status == 1) {
      getUserList(props.folderData.id)
      ElMessage.success(res.message)
      staffAuthDialog.value = false
    } else {
      ElMessage.error(res.message);
      staffAuthDialog.value = false
    }
  })
}
// 多选回调
const handleSelectionChange = (a) => {
  selectionArr.value = a
}
// 新增员工
const addStaff = () => {
  if (selectionArr.value.length > 1) {
    ElMessage.error("一次只能选一位员工");
  } else if (selectionArr.value.length == 0) {
    ElMessage.error("请选择需要添加的员工");
  } else {
    let data = {
      parentid: userInfo.id,
      userid: selectionArr.value[0].userId,
      proid: props.folderData.id,
      auth: staffAuth.value
    }
    api.RelevanceAdd(data).then((res) => {
      if (res.status == 1) {
        getUserList(props.folderData.id)
        ElMessage.success(res.message)
        addStaffDialog.value = false
      }
    })
  }
}
// 删除员工
const staffDelete = (row) => {
  let data = {
    parentid: userInfo.id,
    userid: row.user.id,
    proid: props.folderData.id,
  }
  api.RelevanceDelete(data).then((res) => {
    if (res.status == 1) {
      getUserList(props.folderData.id)
      ElMessage.success(res.message)
    } else {
      ElMessage.error(res.message);
    }
  })
}
// 格式化函数（后期写成公用方法）
const formatAuth = (row, column, cellValue) => {
  return authMap[cellValue] || '未知权限';
}
const getUserList = (id) => {
  api.getUserList({ userid: userInfo.id, proid: id }).then((res) => {
    if (res.status !== 1) {
      console.warn('获取用户列表失败:', res.message || '未知错误');
    } else {
      const userList = res.data.userList.map(item => ({
        userId: item.user.id,
        staffname: item.user.staffname,
        auth: item.auth || '1',
        ...item
      }));
      tableData.value = userList
    }
  })
};
watch(() => props.folderData, async (newVal, oldVal) => {
  if (newVal != {}) {
    getUserList(newVal.id)
    form.value = {
      fileName: newVal.label,
      mode: "1",
    }
  }
}, {
  immediate: true
})
// 组件卸载时取消所有未完成请求
onUnmounted(() => {
  // 取消当前页面的所有请求
  // activeRequests.forEach((cancel) => cancel());
  // activeRequests.length = 0;

  // 取消全局所有未完成的请求
  cancelAllPendingRequests();
})
</script>
<style lang="scss" scoped>
@import "@/assets/scss/web.scss";
</style>